import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { N8nClient } from './n8n-client.js';
import { MCPServer } from './mcp-server.js';

dotenv.config();

console.log('🚀 启动 N8N MCP服务器...\n');

const app = express();
app.use(cors());
app.use(express.json());

// N8N客户端
const n8nClient = new N8nClient(
  process.env.N8N_BASE_URL || 'http://localhost:5678',
  process.env.N8N_API_KEY
);

// MCP服务器
const mcpServer = new MCPServer(n8nClient);

// 健康检查
app.get('/health', async (req, res) => {
  try {
    const n8nHealth = await n8nClient.testConnection();
    res.json({
      status: 'healthy',
      timestamp: new Date().toISOString(),
      mcp_server: 'running',
      n8n_connection: n8nHealth
    });
  } catch (error) {
    res.status(500).json({
      status: 'unhealthy',
      error: error.message
    });
  }
});

// MCP工具列表
app.get('/mcp/tools', async (req, res) => {
  try {
    const result = await mcpServer.server.request({ method: 'tools/list' });
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// MCP工具调用
app.post('/mcp/call', async (req, res) => {
  try {
    const { name, arguments: args } = req.body;
    
    if (!name) {
      return res.status(400).json({ error: '缺少工具名称' });
    }

    const result = await mcpServer.server.request({ 
      method: 'tools/call', 
      params: { name, arguments: args || {} }
    });
    
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 测试N8N连接
app.get('/test', async (req, res) => {
  try {
    const connectionTest = await n8nClient.testConnection();
    
    if (connectionTest.success) {
      const workflows = await n8nClient.getWorkflows();
      res.json({
        connection: connectionTest,
        workflows_count: workflows.length,
        message: '✅ N8N连接正常，MCP服务器就绪'
      });
    } else {
      res.status(500).json({ 
        connection: connectionTest,
        message: '❌ N8N连接失败，请检查配置'
      });
    }
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`📡 HTTP服务器运行在端口 ${PORT}`);
  console.log(`🔗 健康检查: http://localhost:${PORT}/health`);
  console.log(`🧪 测试连接: http://localhost:${PORT}/test`);
  console.log(`🛠️  MCP工具: http://localhost:${PORT}/mcp/tools`);
  console.log('\n准备就绪！可以在Trae中配置此MCP服务器。');
});